package com.gopay.cron.web.controller;

import com.gopay.common.constants.fund.FundFileSourceConstants;
import com.gopay.common.constants.holiday.HolidayType;
import com.gopay.common.domain.fund.vo.FileBizParam;
import com.gopay.common.domain.fund.vo.PageData;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.FastJsonUtil;
import com.gopay.cron.service.fund.FundFastPayService;
import com.gopay.remote.cps.holiday.HolidayRemoteService;
import com.gopay.remote.fundcps.service.FileHandlerService;
import com.gopay.scheduler.service.fund.FundBaseOperateService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * 手动执行基金任务，非专业人员禁止操作。
 *
 * @author <a href="mailto:yhwpeng@126.com">wangdong</a>
 * @date 2017-08-11 09:17:50
 */
@Controller
@RequestMapping("/fund")
public class FundCronController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "fileHandlerService")
    private FileHandlerService fundFileRemoteService;
    @Autowired
    private FundBaseOperateService operateService;

    @Autowired
    private FundFastPayService fundFastPayService;

    @Resource(name = "holidayRemoteService")
    private HolidayRemoteService holidayRemoteService;

    @RequestMapping(value = "/redeemCheck", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String redeemCheck(HttpServletRequest request) throws Exception {
        PageData pd = new PageData(request);
        logger.info("页面传入参数为：{}", FastJsonUtil.toJSONString(pd));
        String settleDay = pd.getString("settleDay");
        try {
            if (!holidayRemoteService.isHoliday(new Date(), HolidayType.FUND_COMPANY)) {
                logger.info("与基金公司赎回分红结果对账文件手动对账开始，清算日期：{}=============", settleDay);
                String res = fundFileRemoteService.redeemCheck(
                        new FileBizParam(settleDay, operateService.queryAllFundCorp(), FundFileSourceConstants.CORN));
                logger.info("与基金公司赎回分红结果对账文件手动对账结束  :  " + res);
            }
        } catch (Exception e) {
            logger.error("与基金公司赎回分红结果对账文件手动对账任务失败！", e);
            return "执行失败！" + e.getMessage();
        }
        return "成功执行！";
    }


    /**
     * 用于手动执行国付宝转基金转账操作，可选择日期及判断是否校验银行通知，用法如下：
     * http://localhost:8017/cron/fund/fund2GopayTransMoney.shtml?key=121&date=20170810&check=true
     * 其中key为当前日期的平方
     * 日期yyyyMMdd及结算日期
     * check用于判断是否对银行通知的金额及订单金额做校验，可不填，默认为true
     *
     * @author <a href="mailto:yhwpeng@126.com">wangdong</a>
     * @date 2017-08-11 10:02:52
     */
    @RequestMapping(value = "/fund2GopayTransMoney", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        PageData pd = new PageData(request);
        logger.info("页面传入参数为：{}", FastJsonUtil.toJSONString(pd));
        String key = pd.getString("key");
        Calendar now = Calendar.getInstance();
        int day = now.get(Calendar.DAY_OF_MONTH);
        String keyCalc = day * day + "";
        if (!key.equals(keyCalc)) {
            return "key不匹配！";
        }
        String settleDay = pd.getString("date");
        if (StringUtils.isBlank(settleDay)) {
            return "日期为空，请检查！";
        }
        if (settleDay.length() != 8) {
            return "日期格式不正确，请检查！";
        }
        Boolean check = true;
        String checkObj = pd.getString("check");
        if (StringUtils.isNotBlank(checkObj)) {
            check = Boolean.parseBoolean(checkObj);
        }
        try {
            logger.info("【手动执行基金转国付宝】开始，清算日期：{}", settleDay);
            FileBizParam fileBizParam = new FileBizParam(settleDay, operateService.queryAllFundCorp(), FundFileSourceConstants.CORN_HANDLE);
            fileBizParam.setCheckNotify(check);
            logger.info("【手动执行基金转国付宝】传入指令：{}", FastJsonUtil.toJSONString(fileBizParam));
            String res = fundFileRemoteService.fund2GopayTransferMoney(fileBizParam);
            logger.info("【手动执行基金转国付宝】结束，返回结果：{}", res);
        } catch (Exception e) {
            logger.error("【手动执行基金转国付宝】异常", e);
            return "执行失败！" + e.getMessage();
        }
        return "成功执行！";
    }

    @RequestMapping(value = "/redeem", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String withdraw(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("【赎回操作任务一】监管行提供给国付宝赎回分红退款文件（0文件）生成定时任务开始！=============" + DateUtils.format(new Date()), DateUtils.yyyy_MM_dd_HH_mm_ss);
        PageData pd = new PageData(request);
        String settleDay = pd.getString("date");
        if (StringUtils.isBlank(settleDay)) {
            logger.error("【赎回操作任务一】日期入参丢失");
        }
        String res = null;
        try {
            logger.info("【赎回操作任务一】获取监管行文件rtfund_redeem_yyyyMMdd.txt 开始");
            List<String> custIds = operateService.pullFileFromSftp(settleDay);
            if (custIds == null || custIds.size() == 0) {
                logger.info("【赎回操作任务一】获取监管行文件结束，今日没有需要处理的数据！");
            } else {
                logger.info("【赎回操作任务一】获取监管行文件结束，今日有数据的基金有：{}，开始联机fundcps", FastJsonUtil.toJSONString(custIds));
                res = fundFileRemoteService.superviseRedeemFile(new FileBizParam(settleDay, custIds, FundFileSourceConstants.CORN));
                logger.info("【赎回操作任务一】联机fundcps结束，返回结果：{}", res);
            }
        } catch (Exception e) {
            logger.error("【赎回操作任务一】获取银行数据异常！", e);
        }
        logger.info("【赎回操作任务一】监管行提供给国付宝赎回分红退款文件（0文件）定时任务执行完毕！");
        return res;
    }

    @RequestMapping(value = "/fastPay", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void fastPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("【活期宝快速赎回付款处理】生成活期宝02018订单，开始！=============" + DateUtils.format(new Date()), DateUtils.yyyy_MM_dd_HH_mm_ss);
        Date startTime = DateUtils.add(new Date(), Calendar.DATE, -7);
        Date endTime = DateUtils.getSystemDate();
        fundFastPayService.fastPay(startTime, endTime);
        logger.info("【活期宝快速赎回付款处理】执行完毕！");
    }


}
